﻿namespace Microsoft.SharePoint.Client
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Threading;
    using System.Windows;

    internal static class UIThreadSynchronizationContextInternal
    {
        private static volatile SynchronizationContext s_current;

        private static void SetCurrentUsingUIThread()
        {
            s_current = SynchronizationContext.Current;
        }

        public static SynchronizationContext Current
        {
            get
            {
                if (s_current == null)
                {
                    if ((ApplicationContext.Current != null) && (ApplicationContext.Current.UIThreadSynchronizationContext != null))
                    {
                        return ApplicationContext.Current.UIThreadSynchronizationContext;
                    }
                    if (!Deployment.Current.Dispatcher.CheckAccess())
                    {
                        ManualResetEvent resetEvent = new ManualResetEvent(false);
                        Deployment.Current.Dispatcher.BeginInvoke(delegate {
                            SetCurrentUsingUIThread();
                            resetEvent.Set();
                        });
                        if (!resetEvent.WaitOne(0x2710))
                        {
                            throw new InvalidOperationException();
                        }
                        resetEvent.Close();
                    }
                    else
                    {
                        SetCurrentUsingUIThread();
                    }
                }
                return s_current;
            }
        }
    }
}

